package com.calmcar.adas.apiserver;

import android.app.Activity;
import android.content.Context;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.util.Log;

import com.calmcar.adas.apiserver.model.CdwDetectInfo;
import com.calmcar.adas.apiserver.model.LdwDetectInfo;
import com.calmcar.adas.apiserver.out.ActiveSuccessListener;
import com.calmcar.adas.apiserver.out.CvCameraViewFrame;
import com.calmcar.adas.apiserver.out.DetectInitSuccessListener;
import com.calmcar.adas.apiserver.out.MatDrawProcessMan;
import com.calmcar.adas.conf.Constant;
import com.calmcar.adas.gps.AdasLocManager;
import com.calmcar.adas.gps.LocationTickListener;
import com.calmcar.adas.serverman.LaneCarServerManager;
import com.calmcar.adas.service.AdasServicePool;
import com.lisence.util.LisenceManager;
import com.lisence.util.NetWorkStateReceiver;

/**
 * Adas服务配置
 */

public class AdasServer {

    private Context mContext;
    private AdasLocManager   adasLocManager;
    private LaneCarServerManager laneCarServerManager;
    private MatDrawProcessMan matDrawProcess;
    private AdasServicePool adasServicePool;
    private SharedPreferences spf=null;
    private LisenceManager lisenceManager;

    static {
        System.loadLibrary("opencv_java3");
        System.loadLibrary("calmcar_adas");
    }

    private static  AdasServer adasServer=null;
    public static  AdasServer getInstance(){
        return  adasServer;
    }


    public double getRate() {
        return adasLocManager.getRate();
    }

    public AdasServer(Context mContext) {
        this.mContext = mContext;
        adasServicePool = new AdasServicePool();
        laneCarServerManager = new LaneCarServerManager(mContext, adasServicePool);
        lisenceManager = new LisenceManager(laneCarServerManager, mContext);
        matDrawProcess = new MatDrawProcessMan(laneCarServerManager.getCdwServerManager());
        Log.i("adas_log","sdk_version:"+AdasConf.SDK_VERSION);
        spf=mContext.getSharedPreferences("adas_vp", Activity.MODE_PRIVATE);
        initVPPara();
        adasServer=this;
    }

    public DetectInitSuccessListener getDetectInitSuccessListener() {
        return detectInitSuccessListener;
    }

    public void setDetectInitSuccessListener(DetectInitSuccessListener detectInitSuccessListener) {
        this.detectInitSuccessListener=detectInitSuccessListener;
    }

    DetectInitSuccessListener detectInitSuccessListener;


    public ActiveSuccessListener getActiveSuccessListener() {
        return activeSuccessListener;
    }

    public void setActiveSuccessListener(ActiveSuccessListener activeSuccessListener) {
        lisenceManager.setActiveSuccessListener(activeSuccessListener);
    }

    ActiveSuccessListener activeSuccessListener;

    /**
     * 开启adas服务
     */
    public void startServer() {
        registerServer();
        lisenceManager.checkLicenceDate();
       laneCarServerManager.init();
        setVPInit();
        startDetectThread();
        initLocationService( mContext,null);
        //提示 初始化成功
        if(detectInitSuccessListener!=null ){
            detectInitSuccessListener.onInitSuccess();
        }
    }

    /**
     * 开启adas服务
     * @param locationTickListener
     */
    public void startServer(LocationTickListener locationTickListener) {
        registerServer();
        lisenceManager.checkLicenceDate();
        laneCarServerManager.init();
        setVPInit();
        startDetectThread();
        initLocationService( mContext,locationTickListener);
        //提示 初始化成功
        if(detectInitSuccessListener!=null ){
            detectInitSuccessListener.onInitSuccess();
        }
    }
    NetWorkStateReceiver netWorkStateReceiver=null;
    public void registerServer(){
        if (netWorkStateReceiver == null) {
            netWorkStateReceiver = new NetWorkStateReceiver(lisenceManager);
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        mContext.registerReceiver(netWorkStateReceiver, filter);
    }


    public void unregisterServer(){
        if(netWorkStateReceiver!=null){
            mContext.unregisterReceiver(netWorkStateReceiver);
            netWorkStateReceiver=null;
        }
    }


    /**
     * @param width                视频宽
     * @param height               视频高
     */
    public void initConf( int width, int height) {
        setInputFrameWidthHeight(width, height);
    }

    /**
     * 退出服务
     */
    public void serverStop() {
        try {
            unregisterServer();
            laneCarServerManager.stopServer();
            adasLocManager.locationProcessServiceStop();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 设置服务开启状态
     *
     * @param isChecked
     * @param type      car:车辆检测  line:车道线检测
     */
    public void openDetect(boolean isChecked, String type) {
        switch (type) {
            case "car":
                AdasConf.CAR_DETECT_OPEN = isChecked;
                if(isChecked){
                    laneCarServerManager.setDetectState(-1,1);
                }else{
                    laneCarServerManager.setDetectState(-1,0);
                }
                break;
            case "line":
                AdasConf.LANE_DETECT_OPEN = isChecked;
                if(isChecked){
                    laneCarServerManager.setDetectState(1,-1);
                }else{
                    laneCarServerManager.setDetectState(0,-1);
                }
                break;
        }
    }


    /**
     * 开启/关闭ADAS全功能
     *
     * @param open
     */
    public void openDetectAll(boolean open) {
        AdasConf.CAR_DETECT_OPEN = open;
        AdasConf.LANE_DETECT_OPEN = open;
        if(open){
            laneCarServerManager.setDetectState(1,1);
        }else{
            laneCarServerManager.setDetectState(0,0);
        }
    }

    /**
     * 相机数据处理异步方法
     *
     * @param inputFrame
     */
    long currentTime=0;
    int tickNumber=0;
    public void  processDataAsyn(CvCameraViewFrame inputFrame) {
        //异步方法--推荐  290->200
        if(System.currentTimeMillis()-currentTime>=250){//250-->50
            currentTime=System.currentTimeMillis();
            sendDataForDetect(inputFrame);
        }
        LdwDetectInfo ldwDetectInfo = laneCarServerManager.getLdwServerManager().getLdwDetectInfo();
        CdwDetectInfo cdwDetectInfo = laneCarServerManager.getCdwServerManager().getCdwDetectInfo();

        //10S ->30帧数据   &&  !AdasConf.CHECK_OK) && ldwDetectInfo.getLdwType()==1
        if(ldwDetectInfo!=null  && ldwDetectInfo.getLdwType() >= 0  ){//
//            int baseValue=10;
//            if(ldwDetectInfo.getVpy0()>AdasConf.VP_X_TEMP-baseValue &&  ldwDetectInfo.getVpy0()<AdasConf.VP_X_TEMP+baseValue
//                    &&  ldwDetectInfo.getVpy1()>AdasConf.VP_Y_TEMP-baseValue  && ldwDetectInfo.getVpy1()<AdasConf.VP_Y_TEMP+baseValue
//                    ){
            tickNumber+=1;
            if(tickNumber>= 10) {//去最后一次数据
                tickNumber=0;
                AdasConf.VP_X_TEMP = (int) ldwDetectInfo.getVpy0();
                AdasConf.VP_Y_TEMP = (int) ldwDetectInfo.getVpy1();
                this.setVPParaAuto((int) ldwDetectInfo.getVpy0(), (int) ldwDetectInfo.getVpy1());
                AdasConf.CHECK_OK = true;
            }
//         }else{
//                AdasConf.VP_X_TEMP=(int)ldwDetectInfo.getVpy0();
//                AdasConf.VP_Y_TEMP=(int)ldwDetectInfo.getVpy1();
//         }
        }

        if(!AdasConf.CHECK_OK){
            if(ldwDetectInfo!=null ){
                ldwDetectInfo.setLdwType(-1);
            }
        }
        matDrawProcess.ProcessLaneValue(ldwDetectInfo);
        matDrawProcess.ProcessCarValue(cdwDetectInfo, ldwDetectInfo, adasLocManager.getRate());

        if(cameraDataProcessCallBack!=null){
            cameraDataProcessCallBack.onProcessBack(ldwDetectInfo, cdwDetectInfo);
        }
    }


    /**
     * 初始化定位服务
     *
     * @param context
     * @param locationTickListener
     */
    public void initLocationService(Context context, LocationTickListener locationTickListener) {
        adasLocManager = new AdasLocManager(context);
        adasLocManager.setLocationTickListener(locationTickListener);
        adasLocManager.locationProcessServiceInitStart();
    }

    /**
     * 车道线检测与车辆检测
     *
     * @param inputStream
     */
    public void sendDataForDetect(CvCameraViewFrame inputStream) {
        laneCarServerManager.sendFrameData(inputStream, adasLocManager.getRate());

    }

    /**
     * 开启检测服务
     */
    public void startDetectThread() {
        laneCarServerManager.startServer();

    }

    /**
     * 定位服务可用状态
     *
     * @return true :可用
     */
    public boolean isValidLocationState() {
        return adasLocManager.isValidLocationState();
    }



    /**
     * 设置开启车道线偏离预警阀值 默认40
     *
     * @param rate
     */
    public void setLaneDetectRate(int rate) {
        Constant.CAR_SPEED_LANE_THRESHOLD = rate;
    }

    /**
     * 开启车辆碰撞预警阈值  默认25
     *
     * @param rate
     */
    public void setCarDetectRate(int rate) {
        Constant.CAR_SPEED_FRONT_THRESHOLD = rate;
    }


    /**
     * 设置视频格式大小及类型
     */
    public void setInputFrameWidthHeight(int width, int height) {
        AdasConf.WIDTH_HEIGHT = width + "*" + height;
        AdasConf.IN_FRAME_WIDTH = width;
        AdasConf.IN_FRAME_HEIGHT = height;
        AdasConf.centerX = width / 2;
        AdasConf.centerY = height / 2;
        if(AdasConf.VP_X==0){
            AdasConf.VP_X=AdasConf.IN_FRAME_WIDTH/2;
            AdasConf.VP_Y=AdasConf.IN_FRAME_HEIGHT/2;
        }
    }

    public CameraDataProcessCallBack getCameraDataProcessCallBack() {
        return cameraDataProcessCallBack;
    }

    public void setCameraDataProcessCallBack(CameraDataProcessCallBack cameraDataProcessCallBack) {
        this.cameraDataProcessCallBack = cameraDataProcessCallBack;
    }

    private  CameraDataProcessCallBack  cameraDataProcessCallBack ;

    public interface CameraDataProcessCallBack {
        void  onProcessBack(LdwDetectInfo ldwDetectInfo, CdwDetectInfo cdwDetectInfo);
    };

    /**
     * 设置偏离预警灵敏度
     */
    private  void  setLaneWarnSensitivity(int type){

    }

    /**
     * 设置前车启动灵敏度
     */
    public void  setFrontCarLaunchSensitivity(int level  ){
        AdasConf.FCW_LAUNCH_LEVEL=level;
        spf.edit().putInt("fcw_launch_level",level).commit();
    }

    /**
     *  获取防碰撞预警灵敏度
     */
    public int  getFrontCarLaunchSensitivity(){
        return   AdasConf.FCW_LAUNCH_LEVEL;
    }



    /**
     *  设置防碰撞预警灵敏度
     * @param level
     * 1-5 默认3
     */
    public void  setFrontCarWarnSencitivity(int level){
        AdasConf.FCW_WARN_LEVEL=level;
        spf.edit().putInt("fcw_warn_level",level).commit();
    }

    /**
     *  获取防碰撞预警灵敏度
     */
    public int  getFrontCarWarnSencitivity(){
        return  AdasConf.FCW_WARN_LEVEL;
    }

    /**
     * 设置视野焦点
     * @param mv_x
     * @param mv_y
     */
    public void setVPPara (int mv_x,int mv_y) {
        AdasConf.VP_X=mv_x;
        AdasConf.VP_Y= mv_y;
        if(laneCarServerManager!=null ){
            laneCarServerManager. setVPPara ( mv_x, mv_y,0);
        }
//        if(cdwServerManager!=null){
//            cdwServerManager. setVPPara ( mv_x,mv_y);
//        }
        spf.edit().putInt("mv_x",mv_x).commit();
        spf.edit().putInt("mv_y",mv_y).commit();

        AdasConf.CHECK_OK=false;
        tickNumber=0;
    }


    /**
     * 设置视野焦点
     * @param mv_x
     * @param mv_y
     */
    public void setVPParaAuto (int mv_x,int mv_y) {
//        AdasConf.VP_X=mv_x;
//        AdasConf.VP_Y= mv_y;
        if(laneCarServerManager!=null){
            laneCarServerManager. setVPPara ( mv_x,mv_y,1);
        }
//        spf.edit().putInt("mv_x",mv_x).commit();
//        spf.edit().putInt("mv_y",mv_y).commit();
    }



    private void setVPInit(){
        if(laneCarServerManager!=null ){
            laneCarServerManager. setVPPara ( (int)AdasConf.VP_X,  (int)AdasConf.VP_Y,0);
        }
        AdasConf.VP_X_TEMP =     AdasConf.VP_X;
        AdasConf.VP_Y_TEMP =    AdasConf.VP_Y;
        AdasConf.CHECK_OK=false;
        tickNumber=0;
    }


    /**
     * 视野焦点
     * @return  {x,y}
     */
    public int[]  getVPPara () {
        int [] result=new int[2];
        result[0]=spf.getInt("mv_x",0);
        result[1]=spf.getInt("mv_y",0);
        if(result[0]==0){
            AdasConf.VP_X=AdasConf.IN_FRAME_WIDTH/2;
            AdasConf.VP_Y=AdasConf.IN_FRAME_HEIGHT/2;
        }
        return  result;
    }

    private void  initVPPara(){
        try{
            AdasConf.VP_X=spf.getInt("mv_x",0);
            AdasConf.VP_Y=spf.getInt("mv_y",0);
            AdasConf.FCW_WARN_LEVEL=spf.getInt("fcw_warn_level",3);
            AdasConf.FCW_LAUNCH_LEVEL=spf.getInt("fcw_launch_level",3);


        }catch (Exception e){
        }
    }


    /**
     *  ADAS SDK VERSION
     * @return
     */
    public String getSdkVersion(){
        return AdasConf.SDK_VERSION;
    }


    /**
     * 设置ADAS运行模式
     * @param mode
     * 0 :室内测试  1：公路模式  默认 1
     */
    public void setAdasServerRunMode(int mode){
        AdasConf.RUN_MODE=mode;
        if(adasLocManager!=null){
            if(AdasConf.RUN_MODE==0){
                adasLocManager.setRate(50.99999);
            }else{
                adasLocManager.setRate(3.6);
            }
        }
    }
    /**
     * 获取ADAS运行模式
     * @param mode
     * 0 :室内测试  1：公路模式  默认 1
     */
    public int   getAdasServerRunMode(int mode){
        return AdasConf.RUN_MODE;
    }

    /**
     *  返回激活状态
     * @return
     */
    public boolean getActiveState(){
        return AdasConf.IS_ACTIVE;
    }

}
